package cn.yuan.xiaoyu.testmodule.view;


import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import java.util.Collections;
import java.util.List;

import cn.yuan.xiaoyu.testmodule.adapter.TestRecycleviewAdapter;

/**
 * Created by yukuoyuan on 2017/5/16.
 */

public class MyItemTouchHelper extends ItemTouchHelper.Callback {
    private TestRecycleviewAdapter testRecycleviewAdapter;
    private List<String> mdata;

    public MyItemTouchHelper(TestRecycleviewAdapter testRecycleviewAdapter, List<String> mdata) {
        this.testRecycleviewAdapter = testRecycleviewAdapter;
        this.mdata = mdata;
    }

    /**
     * 设置支持拖拽和滑动的方向,通过makeMovementFlags设置
     *
     * @param recyclerView
     * @param viewHolder
     * @return
     */
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//上下拖拽
        int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;//左右滑动
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    /**
     * 拖拽时回调
     *
     * @param recyclerView
     * @param viewHolder
     * @param target
     * @return
     */
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        int from = viewHolder.getAdapterPosition();
        int to = target.getAdapterPosition();
        Collections.swap(mdata, from, to);
        testRecycleviewAdapter.notifyDataSetChanged();
        return true;
    }

    /**
     * 滑动时回调的方法
     *
     * @param viewHolder
     * @param direction
     */
    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int position = viewHolder.getAdapterPosition();
        mdata.remove(position);
        testRecycleviewAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        super.onSelectedChanged(viewHolder, actionState);
    }

    /**
     * 用户交互时的回调
     *
     * @param recyclerView
     * @param viewHolder
     */
    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
    }

    /**
     * 是否支持长按拖拽
     *
     * @return
     */
    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }
}
